import logging

from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer

logger = logging.getLogger("django")


def generate_access_token(content: str, expires=None):
    """
    字符串加密
    :param content: 需要加密的字符串
    :param expires: 有效时间，默认有效时间为24小时
    :return: 加密后的字符串
    """
    EXPIRES = 60 * 60 * 24
    if expires is not None and isinstance(expires, int):
        EXPIRES = expires
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires_in=EXPIRES)
    data = {'content': content}
    token = serializer.dumps(data)
    return token.decode()


def check_access_token(token):
    """
    字符串解密
    :param token: 加密后的字符串
    :return: 解密成功返回解密后的字符串，解密失败返回None
    """
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY)
    try:
        data = serializer.loads(token)
    except Exception as e:
        logger.error(e)
        return None
    else:
        return data.get('content')
